import sys
import os
import requests

cwd = os.getcwd()

def print_progress(pre, i:int, t:int):
	p = int(i/t * 100)
	print("\r{}: {} {}%".format(pre, '-'*int(p/5) + ' '*int(100/5-p/5), p), end='')

def download_ts(path, url_list):
	ts_files = []
	i = 0
	for url in url_list:
		i += 1
		print_progress("正在下载", i, len(url_list))
		ts_name = url.split("/")[-1:]
		ts_file = os.path.join(path, ts_name[0])
		if os.path.exists(ts_file):
			ts_files.append(ts_file)
			continue
		with open(ts_file, 'w') as f:
			data = requests.get(url, stream=True)
			for chunk in data.iter_content(chunk_size=512):
				if chunk:
					f.write(chunk)
		ts_files.append(ts_file)

	print("\n下载完成!")
	return ts_files


if __name__=='__main__':
	argv_len = len(sys.argv)

	ts_list = []
	mp4_file = None

	if argv_len == 3:
		m3u8_file, mp4_file = sys.argv[1:]
		print ("开始执行:", m3u8_file, "==>", mp4_file)
		with open(m3u8_file) as m3u8_f:
			content = m3u8_f.readlines()
			for line in content:
				if line.endswith(".ts\n"):
					ts_list.append(line.replace("\n", ""))
					
	ts_path = ts_list[0].split('/')[-2]
	ts_path = os.path.join(cwd, ts_path)
	print ("片段目录:", ts_path)
	ts_file_list = download_ts(ts_path, ts_list)

	mp4_path = os.path.join(cwd, mp4_file)
	with open(mp4_path, 'ab+') as f:
		i = 0
		for ts_file in ts_file_list:
			i += 1
			print_progress("正在转换", i, len(ts_file_list))
			with open(ts_file, 'rb') as ts:
				f.write(ts.read())

		print("\n转换完成!")